package com.newegg.datafeed.adserving.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.newegg.datafeed.adserving.domain.Admin;
import com.newegg.datafeed.adserving.domain.Company;
import com.newegg.datafeed.adserving.domain.User;
import com.newegg.datafeed.adserving.mapper.AdminMapper;
import com.newegg.datafeed.adserving.mapper.CompanyMapper;
import com.newegg.datafeed.adserving.mapper.UserMapper;
import com.newegg.datafeed.adserving.model.UserType;
import com.newegg.datafeed.adserving.response.LoginInfo;
import com.newegg.datafeed.adserving.util.TokenUtil;

@Service
@Transactional
public class LoginService {
	
	@Autowired
	AdminMapper adminMapper;
	
	@Autowired
	CompanyMapper companyMapper;
	
	@Autowired
	UserMapper userMapper;
	
	@Autowired
	TokenUtil tokenUtil;
	
	@Autowired
	ChannelService channelService;
	
	public LoginInfo login(String username, String password, UserType type) {
		switch (type) {
			case ADMIN:{
				return this.adminLogin(username, password);
			}
			case COMPANY:{
				return this.companyLogin(username, password);
			}
			case USER:{
				return this.userLogin(username, password);
			}
		}
		return null;
	}
	
	private LoginInfo adminLogin(String username, String password) {
		Admin account = adminMapper.login(username, password);
		if(account == null){ return null; }
		String security = account.security();
		LoginInfo info = new LoginInfo();
		info.setAccount(account);
		info.setUser(account.getUsername());
		info.setRole(UserType.ADMIN.name());
		info.setToken(tokenUtil.getToken(security));
		info.setChannel(channelService.allKeys());
		return info;
	}
	
	private LoginInfo companyLogin(String username, String password) {
		Company account = companyMapper.login(username, password);
		if(account == null){ return null; }
		String security = account.security();
		LoginInfo info = new LoginInfo();
		info.setAccount(account);
		info.setUser(account.getId() + "");
		info.setRole(UserType.COMPANY.name());
		info.setToken(tokenUtil.getToken(security));
		info.setChannel(channelService.allKeys());
		return info;
	}
	
	private LoginInfo userLogin(String username, String password) {
		User account = userMapper.login(username, password);
		if(account == null){ return null; }
		String security = account.security();
		LoginInfo info = new LoginInfo();
		info.setAccount(account);
		info.setUser(account.getUsername());
		info.setRole(UserType.USER.name());
		info.setToken(tokenUtil.getToken(security));
		info.setChannel(channelService.getUserChannels(username));
		return info;
	}
}
